<template>
  <div class="app-container">
    <el-form
      :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px"
      label-suffix="：">
      <el-row style="display: flex;flex-wrap: wrap">
        <el-col :span="6">
          <el-form-item label="全链路ID" prop="zbitiLogChainId">
            <el-input
              v-model="queryParams.zbitiLogChainId" placeholder="请输入全链路ID" clearable style="width: 220px;"
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="跟踪ID" prop="zbitiLogTraceId">
            <el-input
              v-model="queryParams.zbitiLogTraceId" placeholder="请输入跟踪ID" clearable style="width: 220px;"
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="日志级别" prop="logLevel">
            <el-select
              v-model="queryParams.logLevel" placeholder="日志级别" clearable
              style="width: 220px">
              <el-option
                v-for="dict in logLevelOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="日志内容" prop="logContentLike">
            <el-input
              v-model="queryParams.logContentLike" placeholder="请输入日志内容" clearable style="width: 220px;"
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="类名" prop="clazzLike">
            <el-input
              v-model="queryParams.clazzLike" placeholder="请输入类名" clearable style="width: 220px;"
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="主机名" prop="hostNameLike">
            <el-input
              v-model="queryParams.hostNameLike" placeholder="请输入主机名" clearable style="width: 220px;"
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="IP地址" prop="hostIpLike">
            <el-input
              v-model="queryParams.hostIpLike" placeholder="请输入IP地址" clearable style="width: 220px;"
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="14">
          <el-form-item label="日志时间">
            <el-date-picker
              v-model="dateRange" 
              value-format="YYYY-MM-DD HH:mm:ss.SSS" type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item>
            <search-button @click="handleQuery" :perm="['rule:monitor:runningLog:search']" />
            <reset-button @click="resetQuery" :perm="['rule:monitor:runningLog:update']" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch="showSearch" @query-table="getList" :perm="['rule:monitor:runningLog:search']" />
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ES主键" align="center" prop="_id"  /> -->
      <el-table-column label="日志时间" align="center" width="180" prop="logTime" />
      <el-table-column label="日志级别" align="center" width="90" prop="logLevel">
        <template #default="scope">
          <el-tag v-if="scope.row.logLevel === 'TRACE'">TRACE</el-tag>
          <el-tag v-if="scope.row.logLevel === 'DEBUG'">DEBUG</el-tag>
          <el-tag v-if="scope.row.logLevel === 'INFO'" type="info">INFO</el-tag>
          <el-tag v-if="scope.row.logLevel === 'ERROR'" type="danger">ERROR</el-tag>
          <el-tag v-if="scope.row.logLevel === 'WARN'" type="warning">WARN</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="服务IP地址" align="center" width="180" prop="hostIp" :show-overflow-tooltip="true" />
      <el-table-column label="全链路ID" align="center" width="220" prop="zbitiLogChainId" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-link type="primary" @click="showChainIdLog(scope.row)">{{ scope.row.zbitiLogChainId }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="跟踪ID" align="center" width="220" prop="zbitiLogTraceId" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-link type="primary" @click="showTraceIdLog(scope.row)">{{ scope.row.zbitiLogTraceId }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="线程名" min-width="120" prop="thread" :show-overflow-tooltip="true" />
      <el-table-column label="类名" min-width="220" prop="clazz" :show-overflow-tooltip="true" />
      <el-table-column label="日志内容" align="center" prop="logContent" width="80">
        <template #default="scope">
          <el-link type="primary" @click="showLogDetail(scope.row)">
            详细
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="服务主机名" align="center" min-width="160" prop="hostName" :show-overflow-tooltip="true" />
      <el-table-column label="采集路径" align="center" min-width="200" prop="logPath" :show-overflow-tooltip="true" />
      <el-table-column label="偏移量" align="center" width="100" prop="logOffset" :show-overflow-tooltip="true" />
    </el-table>

    <pagination
      v-show="total>0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog
      width="90%"
      v-el-drag-dialog
      title="日志内容"
      v-model="logDetailVisible"
      @close="closeLogDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div class="log-detail">
        {{ curLogDetailInfo }}
      </div>

      <span class="dialog-footer">
        <el-button type="primary" v-if="afterPageStatus" @click="afterPage()">下一页</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {logSearch} from "@/platform/uni/api/uni/monitor/runningLog.js";
import {formatDate} from "@/utils/index.ts";

export default {
  name: "RuleMonitorRunningLog",
  data() {
    return {
      curData: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 日志级别数据字典
      logLevelOptions: [],
      logDetailVisible: false,
      curLogDetailInfo: '',
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderBy: 'logTime',
        sortDirect: 'DESC',

        // ipaddrLike: undefined,
        // loginNameLike: undefined,
        // status: undefined
      },
      //记录当前页码
      curPageNum: 1,
      //当前链路ID
      curZbitiLogTraceId: '',
      maxIndex: 0,
      afterPageStatus: true,
    };
  },
  created() {
    this.dateRange = [this.getDefaultStartDate(), this.getDefaultEndDate()];
    this.getList();
    this.getDicts("log_level").then(response => {
      this.logLevelOptions = response.data;
    });
  },
  methods: {
    getDefaultStartDate() {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      return formatDate(today)+'.000';
    },
    getDefaultEndDate() {
      const today = new Date();
      const tomorrow = new Date(today);
      tomorrow.setDate(tomorrow.getDate() + 1);
      tomorrow.setHours(0, 0, 0, 0);
      return  formatDate(tomorrow)+'.000';
    },
    /** 查询登录日志列表 */
    getList() {
      this.loading = true;


      logSearch(this.addDateRange(this.queryParams, ['logTimeStart', 'logTimeEnd'], this.dateRange)).then(response => {
          this.list = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    showLogDetail(row) {
      this.logDetailVisible = true
      this.curLogDetailInfo = row.logContent
    },
    showChainIdLog(row) {
      this.curData = {...row, curType: 'zbitiLogChainId'};
      this.curPageNum = 1;
      this.maxIndex = 0;
      this.curLogDetailInfo = '';
      this.listRunningLogs();
    },
    showTraceIdLog(row) {
      this.curData = {...row, curType: 'zbitiLogTraceId'};
      this.curPageNum = 1;
      this.maxIndex = 0;
      this.curLogDetailInfo = '';
      this.listRunningLogs();
    },
    //翻页
    afterPage() {
      this.curPageNum += 1;
      this.listRunningLogs();
    },

    // 加载API日志
    listRunningLogs() {
      this.logDetailVisible = true
      this.loading = true;

      var queryLogParam = {
        "orderBy": "logTime",
        "sortDirect": "DESC",
        "pageSize": this.queryParams.pageSize,
        "pageNum": this.curPageNum
      };
      if (this.curData.curType)
        queryLogParam[this.curData.curType] = this.curData[this.curData.curType];
      logSearch(queryLogParam).then(response => {
          response.data.list.forEach((itemLog, index) => {
            this.curLogDetailInfo += this.maxIndex + index + 1 + '. ' + itemLog.logTime + ' | ' +
              itemLog.hostIp + ' | ' +
              itemLog.logLevel + ' | ' +
              itemLog.zbitiLogChainId + ' | ' +
              itemLog.zbitiLogTraceId + ' | ' +
              itemLog.logContent + '\n\n';
          })
          this.maxIndex += response.data.list.length
          this.loading = false;

          // 最后一页数据，下一页按钮不显示
          this.afterPageStatus = (response.data.list.length >= this.queryParams.pageSize);
        }
      );
    },

    //关闭日志弹窗
    closeLogDialog() {
      this.curLogDetailInfo = '';
      this.curPageNum = 1;
      this.curZbitiLogTraceId = '';
      this.maxIndex = 0;
      this.afterPageStatus = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.log-detail {
  // height: calc(100%-80px);
  overflow: auto;
  white-space: pre-wrap;
}
</style>
